package com.schooldate.Test;


import java.util.ArrayList;
import java.util.List;

import com.schooldate.util.push.PushUtils;
import org.junit.Test;

import com.schooldate.model.entity.ExamSource;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.PropertyNameProcessor;
import org.apache.lucene.search.Query;
import org.apache.poi.POIOLE2TextExtractor;
import org.apache.poi.POITextExtractor;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.extractor.ExtractorFactory;
import org.apache.poi.hdgf.extractor.VisioTextExtractor;
import org.apache.poi.hslf.extractor.PowerPointExtractor;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.model.StyleDescription;
import org.apache.poi.hwpf.model.StyleSheet;
import org.apache.poi.hwpf.usermodel.HeaderStories;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.extractor.ExcelExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.w3c.dom.ranges.Range;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import java.io.FileInputStream;
import java.util.List;
import java.util.UUID;

/**
 * Created by etund on 2015/3/19 0019.
 */

//@ContextConfiguration("/spring-config.xml")
//@RunWith(SpringJUnit4ClassRunner.class)
//@SuppressWarnings("all")
public class CommonTest {
//    @Test
//    public void getCurrentHour() throws Exception{
//        SimpleDateFormat df = new SimpleDateFormat("HH");
//        System.out.println(df.format(new Date()));
//    }
//
//    private boolean isRunning = false;
//
////    @Test
//   public void work() throws Exception{
//        if (!isRunning){
//            Thread.sleep(1000);
//            System.out.println("quartz的任务调度");
//        }
//   }
//
//    @Test
//    public void printSomeThing() throws Exception{
//        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
//        System.out.println(dateFormat.format(new Date()));
//    }

    @Test
    public void testHash() throws Exception {
//        得到文件名的hashCode的值，得到就是fileName这个字符串
        String filename = "标题";
        int hashcode = filename.hashCode();
        int dir1 = hashcode & 0xf;
        int dir2 = (hashcode & 0xf0) >> 4;
        System.out.println(dir1 + "==============================" + dir2);
    }

    @Test
    public void parse2007() throws Exception {
        XWPFDocument docx = new XWPFDocument(POIXMLDocument.openPackage("调查报告-是否应该网购.docx"));
        int pages = docx.getProperties().getExtendedProperties().getUnderlyingProperties().getPages();//总页数
        int wordCount = docx.getProperties().getExtendedProperties().getUnderlyingProperties().getCharacters();// 忽略空格的总字符数 另外还有getCharactersWithSpaces()方法获取带空格的总字数。
        System.out.println("pages=" + pages + " wordCount=" + wordCount);
    }

    @Test
    public void parse97() throws Exception {
        WordExtractor doc = new WordExtractor(new FileInputStream("调查报告-是否应该网购.docx"));
        int pages = doc.getSummaryInformation().getPageCount();//总页数
        int wordCount = doc.getSummaryInformation().getWordCount();//总字符数
        System.out.println("pages=" + pages + " wordCount=" + wordCount);
    }

    public void testWord() throws Exception {
        FileInputStream fis = new FileInputStream("E:\\MEclipse_Workspaces\\MyEclipse Professional\\SchoolDate\\src\\com\\schooldate\\Test\\123.doc");

    }

    @Test
    public void testNew() throws Exception {
        FileInputStream fis = new FileInputStream("E:\\MEclipse_Workspaces\\MyEclipse Professional\\SchoolDate\\src\\com\\schooldate\\Test\\123.doc");
        FileInputStream fis_1 = new FileInputStream("E:\\MEclipse_Workspaces\\MyEclipse Professional\\SchoolDate\\src\\com\\schooldate\\Test\\123.doc");
        HWPFDocument hwpfDocument = new HWPFDocument(fis_1);
        System.out.println(hwpfDocument.getDocumentText());
        POIFSFileSystem fileSystem = new POIFSFileSystem(fis);
        // Firstly, get an extractor for the Workbook
        POIOLE2TextExtractor oleTextExtractor =
                ExtractorFactory.createExtractor(fileSystem);
        if (oleTextExtractor instanceof WordExtractor) {

            WordExtractor wordExtractor_1 = (WordExtractor) oleTextExtractor;
//            for (String paragraph : paragraphText_1) {
//                System.out.println(paragraph);
//            }
            System.out.println("Footer text: " + wordExtractor_1.getCommentsText()[0]);
//            System.out.println("Footer text: " + wordExtractor_1.getText());
            // Then a List of extractors for any embedded Excel, Word, PowerPoint
            // or Visio objects embedded into it.
        }

        POITextExtractor[] embeddedExtractors =
                ExtractorFactory.getEmbededDocsTextExtractors(oleTextExtractor);
        for (POITextExtractor textExtractor : embeddedExtractors) {
            // If the embedded object was an Excel spreadsheet.
            if (textExtractor instanceof ExcelExtractor) {
                ExcelExtractor excelExtractor = (ExcelExtractor) textExtractor;
                System.out.println(excelExtractor.getText());
            }
            // A Word Document
            else if (textExtractor instanceof WordExtractor) {
                WordExtractor wordExtractor = (WordExtractor) textExtractor;
                String[] paragraphText = wordExtractor.getParagraphText();
                for (String paragraph : paragraphText) {
                    System.out.println(paragraph);
                }
                // Display the document's header and footer text
                System.out.println("Footer text: " + wordExtractor.getFooterText());
                System.out.println("Header text: " + wordExtractor.getHeaderText());
            }
            // PowerPoint Presentation.
            else if (textExtractor instanceof PowerPointExtractor) {
                PowerPointExtractor powerPointExtractor =
                        (PowerPointExtractor) textExtractor;
                System.out.println("Text: " + powerPointExtractor.getText());
                System.out.println("Notes: " + powerPointExtractor.getNotes());
            }
            // Visio Drawing
            else if (textExtractor instanceof VisioTextExtractor) {
                VisioTextExtractor visioTextExtractor =
                        (VisioTextExtractor) textExtractor;
                System.out.println("Text: " + visioTextExtractor.getText());
            }
        }
    }

    @Test
    public void testWord_1() throws Exception {
        FileInputStream fis = new FileInputStream("E:\\MEclipse_Workspaces\\MyEclipse Professional\\SchoolDate\\web\\examSource\\11\\15\\373c81c1-4aa0-44af-8f13-173c72d1522a_123.doc");
        HWPFDocument doc = new HWPFDocument(fis);
        org.apache.poi.hwpf.usermodel.Range r = doc.getRange();
        List<String> list = new ArrayList<String>();
        String text = null;
        for (int i = 0; i < r.numParagraphs(); i++) {
            Paragraph p = r.getParagraph(i);
            int numStyles = doc.getStyleSheet().numStyles();
            int styleIndex = p.getStyleIndex();
            if (numStyles > styleIndex) {
                StyleSheet styleSheet = doc.getStyleSheet();
                StyleDescription styleDescription = styleSheet.getStyleDescription(styleIndex);
                String styleName = styleDescription.getName();
                if (styleName != null && styleName.contains("正文")) {
//                    System.out.println(p.text());
//                    list.add(p.text());
//                    System.out.println(text);
                    text += p.text().trim();
                }
            }
        }
//        text += "----------";
        System.out.println(text + "=====");
    }

//    @Test
//     public List<question> search(String queryString) throws IOException{
//            Session session=sessionFactory.openSession();
//            FullTextSession fullTextSession = Search.getFullTextSession(session);
//            QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Question.class).get();
//            //在这里修改要查询的字段
//            System.out.println(queryString);
//            Query luceneQuery = queryBuilder.keyword().onFields("title","content").matching(queryString).createQuery();
//            org.hibernate.Query fullTextQuery = fullTextSession.createFullTextQuery(luceneQuery, Question.class);
//
//            List<question> rsList = fullTextQuery.list();
    //上面是搜索功能的代码，下面是结果集关键字高亮的实现代码
//            SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<font color="red">", "</font>");
//            QueryScorer queryScorer = new QueryScorer(luceneQuery);
//            Highlighter highlighter = new Highlighter(formatter, queryScorer);
//            Analyzer analyzer = new ChineseAnalyzer();
//            String[] fieldNames={"title","content"};
//            for (Question q : rsList) {
//                for (String fieldName : fieldNames) {
//                    //运用反射得到具体的标题内容
//                    Object fieldValue = ReflectionUtils.invokeMethod(BeanUtils.getPropertyDescriptor(Question.class, fieldName).getReadMethod(), q); //ReflectionUtils.getField(ReflectionUtils.findField(searchResultClass, fieldName), e);
//                    String hightLightFieldValue = null;
//                    if(fieldValue instanceof String){
//
//                        try {
//                            //获得高亮关键字
//                            hightLightFieldValue = highlighter.getBestFragment( analyzer, fieldName , ObjectUtils.toString(fieldValue, null));
//                        } catch (IOException e1) {
//                            e1.printStackTrace();
//                        } catch (InvalidTokenOffsetsException e1) {
//                            e1.printStackTrace();
//                        }
//                        //这个判断很关键，否则如果标题或内容中没有关键字的话，就会出现不显示的问题。
//                        if(hightLightFieldValue!=null){
//                            //运用反射设置结果集中的关键字高亮
//                            ReflectionUtils.invokeMethod(BeanUtils.getPropertyDescriptor(Question.class, fieldName).getWriteMethod(), q, hightLightFieldValue); //setField(ReflectionUtils.findField(searchResultClass, fieldName), e, hightLightFieldValue);
//                        }
//                    }
//                }
//            }
//            fullTextSession.close();
//            return rsList;
//    }

    @Autowired
    private SessionFactory sessionFactory;

    @Test
    public void searchTest() throws Exception {
        Session session = sessionFactory.openSession();
        FullTextSession fullTextSession = Search.getFullTextSession(session);
        QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(ExamSource.class).get();
        //在这里修改要查询的字段
        System.out.println("校缘需求描述");
        Query luceneQuery = queryBuilder.keyword().onFields("title", "content").matching("校缘需求描述").createQuery();
        org.hibernate.Query fullTextQuery = fullTextSession.createFullTextQuery(luceneQuery, ExamSource.class);
        List<ExamSource> rsList = fullTextQuery.list();
    }

    @Test
    public void genUUID() throws Exception {
        PushUtils.pushToSingle("42b74bacb28414c856505e2e6d70fe7940540a8c8fa4c728b3338c9ec1575367", "有人送花给你啦！快来看看吧!");
    }

}
